import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import { AllStateTypes } from '@/store/interface'

declare module 'vue-router' {
    interface RouteMeta {
        title?: string
        role?: string
        icon?: any
        sort?: number
        real?: boolean
    }
}

const modules = import.meta.globEager('./modules/**/*.ts')

export const funcRoutes: RouteRecordRaw[] = []

Object.keys(modules).forEach(key => {
    const mod = modules[key].default || {}
    const modList = Array.isArray(mod) ? [...mod] : [mod]
    funcRoutes.push(...modList)
})

funcRoutes.sort((a: any, b: any) => {
    return (a.meta?.sort || 0) - (b.meta?.sort || 0)
})

export const MainRoute: RouteRecordRaw = {
    path: '/',
    name: 'ui.main',
    redirect: '/dashboard',
    meta: {
        title: '主页',
        role: 'auth',
        real: true,
    },
}

export const LoginRoute: RouteRecordRaw = {
    path: '/login',
    name: 'guest.login',
    component: () => import('@/views/login/Index.vue'),
    meta: {
        title: '登录',
        role: '',
        real: true,
    },
}

export const NoauthRoute: RouteRecordRaw = {
    path: '/403',
    name: 'ui.403',
    component: () => import('@/views/403.vue'),
    meta: {
        title: '无权限',
        role: '',
        real: true,
    },
}

const router = createRouter({
    history: createWebHistory(),
    routes: [LoginRoute, MainRoute, NoauthRoute, ...funcRoutes],
    strict: true,
    scrollBehavior: () => ({ left: 0, top: 0 }),
})

router.beforeEach((to, from, next) => {
    // console.log('Route beforeEach ', to, from)
    let state = store.state as AllStateTypes
    // 处理 keep-alive ，不删除，不删除
    //
    // console.log(state.tabs.tabs)
    // if (!state.tabs.tabs.some(tab => tab.name === to.name)) {
    //     to.meta.reload = true
    // } // 不删除，不删除不删除，不删除
    if (to.meta.role) {
        if (state.user.id === '') {
            next({
                name: 'guest.login',
            })
            sessionStorage.clear()
            return
        }
        if (to.meta.role !== 'auth' && to.meta.role != undefined && !to.meta.role.split(',').some(r => state.user.roles.includes(r))) {
            next({
                name: 'ui.403',
            })
            return
        }
    }

    next()
})
router.afterEach((to, from) => {
    if (to.name != 'guest.login' && to.name != 'ui.main' && to.name != 'ui.403') {
        store.commit('tabs/add', { name: to.name, title: to.meta.title })
        store.commit('tabs/setLast', from.name)
    }

    // console.log('Route afterEach ', to, from, error)
})

export default router
